import winston from "winston";
import { type Request, type Response } from "express";

export const logger = winston.createLogger({
    format: winston.format.combine(winston.format.timestamp(), winston.format.ms(), winston.format.errors({ stack: true }), winston.format.splat(), winston.format.json()),
    transports: [
        new winston.transports.Console({
            format: winston.format.combine(
                winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
                winston.format.printf(info => `${info.timestamp} ${info.message}`),
                winston.format.colorize({ all: true })
            )
        })
    ]
});

export function logRequestResponse(req: Request, res: Response, next) {
    const start = process.hrtime();

    res.on("finish", () => {
        const elapsed = process.hrtime(start);
        const responseTime = elapsed[0] * 1000 + elapsed[1] / 1000000; // Convert to milliseconds
        const logMessage = `[${req.method}][${res.statusCode}] ${req.originalUrl} ${responseTime}ms \n${JSON.stringify(req.body)}`;
        logger.info(logMessage);
    });

    next();
}

export default {
    logger,
    logRequestResponse
};
